<template>
  <div class="login-wrap">
    <div class="ms-login">
      <div class="ms-title">日报系统</div>

      <el-form
        :model="param"
        :rules="rules"
        ref="login"
        label-width="0px"
        class="ms-content"
      >
        <el-form-item prop="username">
          <el-input
            ref="usernameRef"
            v-model="param.username"
            placeholder="用户名"
            maxlength="16"
            @keyup.enter="focusInput('passwordRef')"
          >
            <template #prepend>
              <user class="icon" @click="focusInput('usernameRef')" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            ref="passwordRef"
            type="password"
            placeholder="密码"
            v-model="param.password"
            maxlength="18"
            @keyup.enter="onPasswordEnter"
          >
            <template #prepend>
              <lock class="icon" @click="focusInput('passwordRef')" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="isRegist" prop="repeatPassword">
          <el-input
            ref="repeatPasswordRef"
            type="password"
            placeholder="重复密码"
            v-model="param.repeatPassword"
            maxlength="18"
            @keyup.enter="focusInput('nicknameRef')"
          >
            <template #prepend>
              <lock class="icon" @click="focusInput('repeatPasswordRef')" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="isRegist" prop="nickname">
          <el-input
            ref="nicknameRef"
            v-model="param.nickname"
            placeholder="你的昵称"
            maxlength="16"
            @keyup.enter="submitFormMethod"
          >
            <template #prepend>
              <user class="icon" @click="focusInput('nicknameRef')" />
            </template>
          </el-input>
        </el-form-item>

        <div class="login-btn">
          <el-button
            type="primary"
            @click="submitFormMethod"
            :loading="submitLoading"
          >
            {{ isRegist ? "注册" : "登录" }}
          </el-button>
        </div>

        <p v-if="isRegist" class="login-tips">
          提示 : 已经注册？点击开始
          <span
            style="color: #67c23a; cursor: pointer"
            @click="toggleRegMethod"
          >
            登录
          </span>
        </p>
        <p v-else class="login-tips">
          提示 : 还没注册？点击开始
          <span
            style="color: #67c23a; cursor: pointer"
            @click="toggleRegMethod"
          >
            注册
          </span>
        </p>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, getCurrentInstance } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { REMEMBER_PASSWORD } from "../../utils/keysManage/localKeys";
import { setCookie, getCookie } from "../../utils/cookies";
import { encryptData, decryptData } from "../../utils/crypto";

export default {
  setup(props, context) {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const router = useRouter();
    const store = useStore();

    // 表单绑定的数据
    const param = reactive({
      username: "",
      password: "",
      repeatPassword: "",
      nickname: "",
    });

    // 是否是注册，默认否
    const isRegist = ref(false);

    // 记住密码（方便登录）
    let rememberPassword = window.localStorage.getItem(REMEMBER_PASSWORD);
    if (rememberPassword) {
      rememberPassword = JSON.parse(rememberPassword);
      param.username = rememberPassword.username || "";
      param.password = decryptData(rememberPassword.password);
    }

    // 表单校验规则
    const rules = reactive({
      username: [
        {
          required: true,
          message: "请输入用户名",
          trigger: "blur",
        },
      ],
      password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      repeatPassword: [
        {
          required: isRegist.value,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请重复输入密码"));
            } else if (value !== param.password) {
              callback(new Error("重复密码不一致"));
            } else {
              callback();
            }
          },
        },
      ],
      nickname: [
        {
          required: isRegist.value,
          trigger: "blur",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请输入你的昵称"));
            } else {
              callback();
            }
          },
        },
      ],
    });

    const login = ref(null);
    const submitLoading = ref(false);

    const toggleRegMethod = () => {
      if (submitLoading.value) return;
      isRegist.value = !isRegist.value;
    };

    // 提交表单
    const submitFormMethod = () => {
      if (submitLoading.value) return;
      login.value.validate((valid) => {
        if (valid) {
          submitLoading.value = true;
          if (isRegist.value) {
            regMethod(param);
          } else {
            loginMethod(param);
          }
        } else {
          // ElMessage.error("登录失败");
          // return false;
        }
      });
    };

    const regMethod = (param) => {
      $api.users
        .reg(param)
        .then((res) => {
          console.log("reg => res ", res);
          ElMessage.success("注册成功，请登录！");
          submitLoading.value = false;
          toggleRegMethod();
        })
        .catch((err) => {
          submitLoading.value = false;
          console.error("reg error: ", err);
        });
    };

    const loginMethod = (param) => {
      $api.users
        .login(param)
        .then((res) => {
          console.log("login =>res ", res);
          ElMessage.success("登录成功");
          window.localStorage.setItem(
            REMEMBER_PASSWORD,
            JSON.stringify({
              username: param.username || "",
              password: encryptData(param.password),
            })
          );
          store.commit("user/login", res.data);
          router.push("/");
        })
        .catch((err) => {
          console.error("login error: ", err);
        })
        .finally(() => {
          submitLoading.value = false;
        });
    };

    const usernameRef = ref(null);
    const passwordRef = ref(null);
    const repeatPasswordRef = ref(null);
    const nicknameRef = ref(null);
    const focusInput = (refKey) => {
      switch (refKey) {
        case "usernameRef":
          usernameRef.value.focus();
          break;
        case "passwordRef":
          passwordRef.value.focus();
          break;
        case "repeatPasswordRef":
          repeatPasswordRef.value.focus();
          break;
        case "nicknameRef":
          nicknameRef.value.focus();
          break;
      }
    };

    // 密码输入框回车事件
    const onPasswordEnter = () => {
      if (isRegist.value) {
        focusInput("repeatPasswordRef");
      } else {
        submitFormMethod();
      }
    };

    // 清除缓存的标签导航
    store.commit("clearTags");

    return {
      param, // 表单绑定的数据
      rules, // 表单校验规则
      login, // 表单的引用
      submitLoading, // 提交按钮的loading状态
      isRegist, // 是否是注册，默认否
      submitFormMethod, // 提交表单
      toggleRegMethod, // 切换登录/注册
      regMethod, // 注册
      loginMethod, // 登录
      usernameRef,
      passwordRef,
      repeatPasswordRef,
      nicknameRef,
      focusInput,
      onPasswordEnter,
    };
  },
};
</script>

<style lang="less" scoped>
.login-wrap {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: url(../../assets/img/login-bg.jpg);
  background-size: 100%;
}
.ms-title {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #fff;
  border-bottom: 1px solid #ddd;
}
.ms-login {
  position: absolute;
  left: 50%;
  top: 50%;
  width: 350px;
  margin: -190px 0 0 -175px;
  border-radius: 5px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}
.ms-content {
  padding: 30px 30px;
}
.login-btn {
  text-align: center;
}
.login-btn button {
  width: 100%;
  height: 36px;
  margin-bottom: 10px;
}
.login-tips {
  font-size: 12px;
  line-height: 30px;
  color: #666;
}
.icon {
  // color: #f56c6c;
  cursor: pointer;
  width: 1.2em;
  height: 1.2em;
}
</style>
